//
//  WBNetworkManager+extension.swift
//  传智微博
//
//  Created by zuxi li on 2017/3/17.
//  Copyright © 2017年 lingtu. All rights reserved.
//

import Foundation


// MARK: - 封装新浪微博的网路请求方法
extension WBNetworkManager{
    
    ///
    ///
    /// -
    
    /// 加载微博数据字典数组
    ///
    /// - Parameters:
    ///   - since_id: 返回iD比since_id大的微博（即since_id时间晚的微博）,默认为0
    ///   - max_id: 返回iD比since_id小的微博）,默认为0
    /// - Parameter completion: 完成回调[list:微博字典数组， 是否成功]
    func statusList(since_id: Int64 = 0, max_id: Int64 = 0, completion:@escaping (_ list: [[String: AnyObject]]?, _ isSuccess: Bool)->()) {
        
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        let params = ["since_id": since_id, "max_id": max_id > 0 ? max_id - 1 : 0]
        
        tokenRequest(URLString: urlString, parameters: params as [String : AnyObject]? ) { (json, isSuccess) in
//            print(json ?? "")
            // 从json中获取statues字典数组
            // 如果 as？ 失败，result = nil
            // 提示： 服务器返回的字典数组，就是按时间倒序排序的
            let jsonn = json as AnyObject
            let result = jsonn["statuses"] as? [[String: AnyObject]]
            completion(result, isSuccess)
        }
    }
    
    // 定时刷新不需要返回失败
    func unreadCount(completion:@escaping (_ count: Int)->()) {
        guard let uid = userAccont.uid else {
            return
        }
        let urlStr = "https://rm.api.weibo.com/2/remind/unread_count.json"
        let params = ["uid": uid]
        tokenRequest(URLString: urlStr, parameters: params as [String : AnyObject]?) { (json, isSuccess) in
            print(json ?? "")
            let dict = json as? [String: AnyObject]
            let count = dict?["status"] as! Int
            completion(count)
        }
    }
}

// MARK: - 用户信息
extension WBNetworkManager {
    
    /// 加载用户信息 用户登录后立即执行
    func loadUserInfo(completion:@escaping(_ dict: [String: AnyObject])->()) {
        let urlString = "https://api.weibo.com/2/users/show.json"
        guard let uid = userAccont.uid else {
            return
        }
        let params = ["uid": uid]
        tokenRequest(URLString: urlString, parameters: params as [String : AnyObject]?) { (json, isSuccess) in
//            print(json ?? "")
            // 完成回调
            completion(json as? [String: AnyObject] ?? [:])
        }
    }
}

// MARK: - OAuth相关
extension WBNetworkManager {
    
    /// 加载accessToken
    /*
     异步到底应该返回什么?  需要什么返回什么
 */
    
    /// 加载AccessToken
    ///
    /// - Parameters:
    ///   - code: 授权码
    ///   - completion: 完成回调[是否成功]
    func loadAccessToken(code: String, completion:@escaping (_ isSuccess: Bool)->()) {
 
        let  urlString = "https://api.weibo.com/oauth2/access_token"
        let params = ["client_id": WBAppKey,
                      "client_secret": WBAppSecret,
                      "grant_type": "authorization_code",
                      "code": code,
                      "redirect_uri": WBRedirectURL,]
        request(method: .POST, URLString: urlString, parameters: params as [String : AnyObject]?) { (json, isSuccess) in
            print(json ?? "")
            // 如果请求失败对用户数据不会有任何影响
            // 直接用字典设置 userAccount
            self.userAccont.yy_modelSet(with: (json as? [AnyHashable : Any]) ?? [:])
            print(self.userAccont)
            
            // 加载当前用户信息
            self.loadUserInfo(completion: { (dict) in
                print(dict)
                
                // 使用用户信息字典设置用户账户信息（昵称和头像地址）
                self.userAccont.yy_modelSet(with: dict)
                print(self.userAccont)
                // 保存模型
                self.userAccont.saveAccount()
                // 用户信息加载完成再回调
                completion(isSuccess)
            })
            
        }
        
    }
}
